package org.darkforest.admin.controller;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.util.CellRangeAddress;
import org.darkforest.common.services.*;
import org.darkforest.common.logger.Logger;
import org.darkforest.common.alipay.util.AlipayNotify;
import org.darkforest.common.util.DateUtil;
import org.darkforest.common.util.JacksonsUtil;
import org.darkforest.dao.mapper.ComplainTalkMapper;
import org.darkforest.dao.mapper.RefundReasonMapper;
import org.darkforest.model.*;
import org.darkforest.ucenter.auth.AuthPassport;
import org.darkforest.ucenter.service.ComplainService;
import org.darkforest.vo.AjaxReturnData;
import org.darkforest.vo.MemberBase;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

/**
 * Created by valentina on 15/5/11.
 * 交易/订单控制类
 */
@Controller
@RequestMapping("trade")
public class TradeController {

    org.slf4j.Logger logger = LoggerFactory.getLogger(TradeController.class);

    @Autowired
    private RefundReturnService refundReturnService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderPayService orderPayService;
    @Autowired
    private WxJSSdkService wxJSSdkService;
    @Autowired
    private ConsultService consultService;
    @Autowired
    private EvaluateGoodsService evaluateGoodsService;
    @Autowired
    private ComplainService complaintService;
    @Autowired
    private ComplainSubjectService complainSubjectService;
    @Autowired
    private ComplainTalkMapper complainTalkMapper;
    @Autowired
    private RefundReasonMapper refundReasonMapper;


    /**
     * 退款
     * @return
     */
    @RequestMapping("refund")
    public ModelAndView refund(RefundReturnSearchBean page){
        ModelAndView modelAndView = new ModelAndView("trade/refund/refund_list");
        page.setRefundType(1);
        refundReturnService.selectListByCondition(page);
        modelAndView.addObject("page",page);
        return modelAndView;
    }

    /**
     * 单条退款
     * @return
     */
    @AuthPassport
    @RequestMapping("refundDo")
    public ModelAndView refundDo(Integer refundId,HttpSession session){
        MemberBase adminInfo = (MemberBase)session.getAttribute("memInfo");

        ModelAndView modelAndView = new ModelAndView("redirect:refund");
//        modelAndView = refundReturnService.refundDo(refundId,modelAndView,adminInfo);
//        Map<String,Object> mapParam = new HashMap<String,Object>();
//        RefundReturn refund = refundReturnService.getRefundReturnById(refundId);
//        if("1".equals(refund.getReturnChannel())){ //微信退款
//            boolean res = wxJSSdkService.wxRefund(refund,adminInfo);
//        }else if("2".equals(refund.getReturnChannel())){ //支付宝退款
//            OrderPay orderPay = new OrderPay();
//            orderPay.setOrderSn(refund.getOrderSn());
//            List<OrderPay> orderPayList = orderPayService.findOrderPayInfoByCondition(orderPay);
//            StringBuffer sb = new StringBuffer();
////        for (OrderPay pay :orderPayList) {
////        }
//            if (orderPayList.size()>0&&orderPayList!=null){
//                sb.append(orderPayList.get(0).getPaySn()).append("^");
//            }
////        sb.append("2015082500001000260060623316").append("^");
//            sb.append(refund.getRefundAmount()).append("^");
//            sb.append(refund.getReasonInfo());
//            mapParam.put("batch_num", "1");
//            System.out.println(sb.toString());
//            mapParam.put("detail_data", sb.toString());
//            String html = alipayService.buildRequestForm(mapParam);
//            modelAndView.addObject("html",html);
//        } else if("3".equals(refund.getReturnChannel())){ //余额退款
//            OrderPay orderPay = new OrderPay();
//            orderPay.setOrderSn(refund.getOrderSn());
//            List<OrderPay> orderPayList = orderPayService.findOrderPayInfoByCondition(orderPay);
//            if (orderPayList.size()>0&&orderPayList!=null){
//                refundReturnService.refundForPdAmount(orderPayList.get(0).getPaySn(), refund.getRefundAmount(), adminInfo);
//            }
//            modelAndView.setViewName("trade/refund/refund");
//        } else if("4".equals(refund.getReturnChannel())){ //余额微信退款
//            Logger.debug(TradeController.class, "余额微信退款");
//            int i =0;
//            OrderPay orderPay = new OrderPay();
//            orderPay.setOrderSn(refund.getOrderSn());
//            List<OrderPay> orderPayList = orderPayService.findOrderPayInfoByCondition(orderPay);
//            if (orderPayList.size()>0&&orderPayList!=null){
//                PayInfoVo order = orderService.getPayInfoByPayno(orderPayList.get(0).getPaySn());
//                //先退余额
//                i = refundReturnService.refundForPdAmount(orderPayList.get(0).getPaySn(), order.getPdAmount(), adminInfo);
//            }
//            modelAndView.setViewName("trade/refund/refund");
//            if(i==1) {
//                boolean res = wxJSSdkService.wxRefund(refund,adminInfo);
//            }
//        }else if("5".equals(refund.getReturnChannel())){ //余额支付宝退款
//            Logger.debug(TradeController.class, "余额支付宝退款");
//            OrderPay orderPay = new OrderPay();
//            orderPay.setOrderSn(refund.getOrderSn());
//            List<OrderPay> orderPayList = orderPayService.findOrderPayInfoByCondition(orderPay);
//            StringBuffer sb = new StringBuffer();
//            int i =0;
//            if (orderPayList.size()>0&&orderPayList!=null){
//                sb.append(orderPayList.get(0).getPaySn()).append("^");
//                PayInfoVo order = orderService.getPayInfoByPayno(orderPayList.get(0).getPaySn());
//                //先退余额
//               i = refundReturnService.refundForPdAmount(orderPayList.get(0).getPaySn(), order.getPdAmount(), adminInfo);
//            }
//            if(i==1) {
//                sb.append(refund.getRefundAmount()).append("^");
//                sb.append(refund.getReasonInfo());
//                mapParam.put("batch_num", "1");
//                System.out.println(sb.toString());
//                mapParam.put("detail_data", sb.toString());
//                String html = alipayService.buildRequestForm(mapParam);
//                modelAndView.addObject("html",html);
//            }
//        }

        return modelAndView;
    }

    /**
     * 批量退款
     * @return
     */
    @RequestMapping("selRefundDo")
    public ModelAndView refundDo(HttpServletRequest request){
        ModelAndView modelAndView = new ModelAndView("trade/refund/refund_url");
        String[] refundIds = request.getParameterValues("refundId");
        StringBuffer sb = new StringBuffer();
        for(int i = 0 ;i<refundIds.length;i++ ){
            RefundReturn refund = refundReturnService.getRefundReturnById(Integer.valueOf(refundIds[i]));
            Order order = orderService.selectOrderByPrimaryKey(refund.getOrderId());
            sb.append(order.getPaySn()).append("^");
            sb.append(refund.getRefundAmount()).append("^");
            sb.append(refund.getReasonInfo());
            if(refundIds.length>1&&i!=refundIds.length-1) {
                sb.append("#");
            }
        }
        Map<String,Object> mapParam = new HashMap<String,Object>();
        mapParam.put("batch_num", String.valueOf(refundIds.length));
        Logger.debug(TradeController.class, "批量退款信息"+sb.toString());
        mapParam.put("detail_data", sb.toString());
//        String html = alipayService.buildRequestForm(mapParam);
//        modelAndView.addObject("html",html);
        return modelAndView;
    }

    /**
     * 退款后回掉
     * @param request
     * @return
     * @throws UnsupportedEncodingException
     */
    @RequestMapping("refundNotifyUrl")
    public ModelAndView refundNotifyUrl(HttpServletRequest request)throws UnsupportedEncodingException {
        ModelAndView modelAndView = new ModelAndView("trade/refund/refund");
        //获取支付宝POST过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
            params.put(name, valueStr);
        }

        //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
        //批次号

        String batch_no = new String(request.getParameter("batch_no").getBytes("ISO-8859-1"),"UTF-8");

        //批量退款数据中转账成功的笔数

        String success_num = new String(request.getParameter("success_num").getBytes("ISO-8859-1"),"UTF-8");

        //批量退款数据中的详细信息
        String result_details = new String(request.getParameter("result_details").getBytes("ISO-8859-1"),"UTF-8");

        //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//

        if(AlipayNotify.verify(params)){//验证成功
            System.out.println("success");
            try {
                String[] details = result_details.split("#");
                for (String detail:details) {
                    String[] data = detail.split("\\^");
//                    List<OrderPay> pays = orderPayService.selectByPaySn(data[0]);
//                    refundReturnService.refundReturnSuccessUpdate(pays.get(0));
                }
            }catch (Exception e){
                e.printStackTrace();
                System.out.println("退款异常");
            }

        }else{//验证失败 z
            System.out.println("fail");
        }
        return modelAndView;
    }

    /**
     * 退货
     * @return
     */
    @RequestMapping("return")
    public ModelAndView returnOfGoods(RefundReturnSearchBean page){
        ModelAndView modelAndView = new ModelAndView("trade/refund/return_list");
        page.setRefundType(2);
        refundReturnService.selectListByCondition(page);
        modelAndView.addObject("page",page);
        return modelAndView;
    }

    /**
     * 订单列表
     * @return
     */
    @RequestMapping("order")
    public ModelAndView order(OrderSearchBean page){
        ModelAndView modelAndView = new ModelAndView("trade/order/order");
        page.setOrderByColume("add_time");
        page.setOrderByType("DESC");
        page.setResultList(orderService.selectListByCondition(page));
        modelAndView.addObject("page",page);
        return modelAndView;
    }

    @RequestMapping("orderExport")
    @ResponseBody
    public AjaxReturnData export(HttpServletRequest request, OrderSearchBean page) {

        AjaxReturnData ajaxReturnData = new AjaxReturnData();

        try {

            //  检索条件的设定
            page.setOrderByColume("add_time");
            page.setOrderByType("DESC");
            page.setPageSwitch(false);

            // 查询结果
            List<OrderVo> orderVoList = orderService.selectListByCondition(page);

            // 导出EXCEL的设定
            HSSFWorkbook workbook = new HSSFWorkbook();

            //新建sheet页
            HSSFSheet sheet = workbook.createSheet("orders");

            int rowIndex = 0;
            int colIndex = 0;

            // 标题
            HSSFRow row = sheet.createRow(rowIndex++);
            String[] titleName = { "序号", "下单日期", "订单编号", "店铺名称", "下单账户名称",
                    "产品名称", "规格", "数量", "成本单价", "成本金额", "销售单价", "销售金额",
                    "支付方式", "支付手续费（扣点）", "实际收款金额", "收件人姓名", "地址", "联系电话", "发票信息", "留言", "备注"};

            // 列宽(自适应宽度用)
            int[] colWidth = {2050, 10, 5120, 10, 3072, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 3072, 6400, 10, 10};

            // 设置字体
            CellStyle style = workbook.createCellStyle();
            HSSFFont font = workbook.createFont();
            // font.setBold(true);
            font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
            //style.setAlignment(HorizontalAlignment.CENTER);
            style.setAlignment(CellStyle.ALIGN_CENTER);
            style.setFont(font);

            HSSFCell cell;
            for (int i = 0; i < titleName.length; i++) {
                cell = row.createCell(i);
                cell.setCellValue(titleName[i]);
                cell.setCellStyle(style);

                // 每一列中的最大值乘一个系数(汉字是512，数字是256.)
                int length = titleName[i].length();
                if (length > colWidth[i] / 512) {     // 列宽
                    colWidth[i] = length * 512;
                }
            }

            // 发票换行
            CellStyle cellStyle = workbook.createCellStyle();

            if (orderVoList != null && orderVoList.size() > 0) {
                for (OrderVo order : orderVoList) {
                    row = sheet.createRow(rowIndex++);
                    colIndex = 0;

                    // 商品信息
                    List<OrderGoods> goodsList = order.getGoods();

                    // 序号
                    mergeRows(sheet, rowIndex, colIndex, goodsList.size());   // 单元格合并
                    if (String.valueOf(colIndex).length() > colWidth[colIndex] / 256) {     // 列宽
                        colWidth[colIndex] = String.valueOf(colIndex).length() * 256;
                    }
                    cell = row.createCell(colIndex++);
                    cell.setCellValue(rowIndex-1);
                    // 下单日期
                    mergeRows(sheet, rowIndex, colIndex, goodsList.size());   // 单元格合并
                    if (order.getAddTimeStr().length() > colWidth[colIndex] / 256) {     // 列宽
                        colWidth[colIndex] = order.getAddTimeStr().length() * 256;
                    }
                    cell = row.createCell(colIndex++);
                    cell.setCellValue(order.getAddTimeStr());
                    // 订单编号
                    mergeRows(sheet, rowIndex, colIndex, goodsList.size());   // 单元格合并
                    if (order.getOrderSn().toString().length() > colWidth[colIndex] / 256) {     // 列宽
                        colWidth[colIndex] = order.getOrderSn().toString().length() * 256;
                    }
                    cell = row.createCell(colIndex++);
                    cell.setCellValue(order.getOrderSn().toString());
                    // 店铺名称
                    mergeRows(sheet, rowIndex, colIndex, goodsList.size());   // 单元格合并
                    cell = row.createCell(colIndex++);
                    if(StringUtils.isNotEmpty(order.getStoreName())) {
                        if (order.getStoreName().length() > colWidth[colIndex-1] / 256) {     // 列宽
                            colWidth[colIndex-1] = order.getStoreName().length() * 256;
                        }
                        cell.setCellValue(order.getStoreName());
                    }
                    // 下单账户名称
                    mergeRows(sheet, rowIndex, colIndex, goodsList.size());   // 单元格合并
                    cell = row.createCell(colIndex++);
                    if(StringUtils.isNotEmpty(order.getBuyerName())) {
                        if (order.getBuyerName().length() > colWidth[colIndex-1] / 256) {     // 列宽
                            colWidth[colIndex-1] = order.getBuyerName().length() * 256;
                        }
                        cell.setCellValue(order.getBuyerName());
                    }
                    // 商品信息
                    // 第一件商品
                    OrderGoods goods = goodsList.get(0);
                    // 产品名称
                    cell = row.createCell(colIndex++);
                    if(StringUtils.isNotEmpty(goods.getGoodsName())) {
                        if (goods.getGoodsName().length() > colWidth[colIndex-1] / 256) {     // 列宽
                            colWidth[colIndex-1] = goods.getGoodsName().length() * 256;
                        }
                        cell.setCellValue(goods.getGoodsName());
                    }
                    // 商品规格
                    String goodsSpec = goods.getGoodsSpec();
                    if ("N;".equals(goodsSpec)) {
                        goodsSpec = "默认";
                    }
                    cell = row.createCell(colIndex++);
                    if(StringUtils.isNotEmpty(goodsSpec)) {
                        if (goodsSpec.length() > colWidth[colIndex-1] / 256) {     // 列宽
                            colWidth[colIndex-1] = goodsSpec.length() * 256;
                        }
                        cell.setCellValue(goodsSpec);
                    }
                    // 商品数量
                    cell = row.createCell(colIndex++);
                    if (goods.getGoodsNum() != null) {
                        if (goods.getGoodsNum().toString().length() > colWidth[colIndex-1] / 256) {     // 列宽
                            colWidth[colIndex-1] = goods.getGoodsNum().toString().length() * 256;
                        }
                        cell.setCellValue(goods.getGoodsNum());
                    }
                    // 成本单价
                    cell = row.createCell(colIndex++);
                    if (goods.getCostPrice() != null) {
                        if (goods.getCostPrice().toEngineeringString().length() > colWidth[colIndex-1] / 256) {     // 列宽
                            colWidth[colIndex-1] = goods.getCostPrice().toEngineeringString().length() * 256;
                        }
                        cell.setCellValue(goods.getCostPrice().toEngineeringString());
                    }
                    // 成本金额
                    cell = row.createCell(colIndex++);
                    if (goods.getGoodsNum() != null && goods.getCostPrice() != null) {
                        BigDecimal costAmount = goods.getCostPrice().multiply(new BigDecimal(goods.getGoodsNum()));
                        if (costAmount.toEngineeringString().length() > colWidth[colIndex-1] / 256) {     // 列宽
                            colWidth[colIndex-1] = costAmount.toEngineeringString().length() * 256;
                        }
                        cell.setCellValue(costAmount.toEngineeringString());
                    }
                    // 销售单价
                    cell = row.createCell(colIndex++);
                    if (goods.getGoodsPrice() != null) {
                        if (goods.getGoodsPrice().toEngineeringString().length() > colWidth[colIndex-1] / 256) {     // 列宽
                            colWidth[colIndex-1] = goods.getGoodsPrice().toEngineeringString().length() * 256;
                        }
                        cell.setCellValue(goods.getGoodsPrice().toEngineeringString());
                    }
                    // 销售金额
                    cell = row.createCell(colIndex++);
                    if (goods.getGoodsNum() != null && goods.getGoodsPrice() != null) {
                        BigDecimal marketAmount = goods.getGoodsPrice().multiply(new BigDecimal(goods.getGoodsNum()));
                        if (marketAmount.toEngineeringString().length() > colWidth[colIndex-1] / 256) {     // 列宽
                            colWidth[colIndex-1] = marketAmount.toEngineeringString().length() * 256;
                        }
                        cell.setCellValue(marketAmount.toEngineeringString());
                    }

                    // 支付方式
                    String payment = "";
//                    if ("1".equals(order.getPaymentCode())) {
//                        payment = "微信";
//                    } else  if ("2".equals(order.getPaymentCode())) {
//                        payment = "支付宝";
//                    } else  if ("3".equals(order.getPaymentCode())) {
//                        payment = "余额支付";
//                    } else if ("4".equals(order.getPaymentCode())) {
//                        payment = "余额加微信支付";
//                    } else if ("5".equals(order.getPaymentCode())) {
//                        payment = "余额加支付宝";
//                    } else {
//                        payment = "其他";
//                    }
                    //  参照商家的（org.darkforest.model.Order  getPaymentName）
                    if (order.getPaymentCode() == null) {
                        payment = "未知";
                    } else if ("1".equals(order.getPaymentCode())) {
                        payment = "微信";
                    } else if ("2".equals(order.getPaymentCode())) {
                        payment = "余额";
                    } else if ("3".equals(order.getPaymentCode())) {
                        payment = "领取";
                    } else if ("4".equals(order.getPaymentCode())) {
                        payment = "余额和微信";
                    } else {
                        payment = "余额和支付宝";
                    }
                    mergeRows(sheet, rowIndex, colIndex, goodsList.size());   // 单元格合并
                    if (payment.length() > colWidth[colIndex] / 256) {     // 列宽
                        colWidth[colIndex] = payment.length() * 256;
                    }
                    cell = row.createCell(colIndex++);
                    cell.setCellValue(payment);
                    // 订单总价格
                    mergeRows(sheet, rowIndex, colIndex, goodsList.size());   // 单元格合并
                    BigDecimal orderAmount =  order.getOrderAmount();
                    BigDecimal actualAmount =  order.getOrderAmount();  // 实际收款金额
                    cell = row.createCell(colIndex++);
                    if (orderAmount != null) {
                        // 支付手续费（扣点）  千分之六
                        BigDecimal fee = orderAmount.multiply(new BigDecimal(0.006));
                        fee = fee.setScale(2, RoundingMode.HALF_UP);
                        if (fee.toEngineeringString().length() > colWidth[colIndex-1] / 256) {     // 列宽
                            colWidth[colIndex-1] = fee.toEngineeringString().length() * 256;
                        }
                        cell.setCellValue(fee.toEngineeringString());
                        // 实际收款金额
                        actualAmount = actualAmount.subtract(fee);
                        actualAmount = actualAmount.setScale(2, RoundingMode.HALF_UP);
                    }
                    // 实际收款金额
                    mergeRows(sheet, rowIndex, colIndex, goodsList.size());   // 单元格合并
                    cell = row.createCell(colIndex++);
                    if (actualAmount != null) {
                        if (actualAmount.toEngineeringString().length() > colWidth[colIndex-1] / 256) {     // 列宽
                            colWidth[colIndex-1] = actualAmount.toEngineeringString().length() * 256;
                        }
                        cell.setCellValue(actualAmount.toEngineeringString());
                    }
                    // 收件人姓名
                    mergeRows(sheet, rowIndex, colIndex, goodsList.size());   // 单元格合并
                    cell = row.createCell(colIndex++);
                    if(StringUtils.isNotEmpty(order.getCommon().getReciverName())) {
                        cell.setCellValue(order.getCommon().getReciverName());
                        if (order.getCommon().getReciverName().length() > colWidth[colIndex-1] / 256) {     // 列宽
                            colWidth[colIndex-1] = order.getCommon().getReciverName().length() * 256;
                        }
                    }
                    // 收货人其它信息
                    Address address = new Address();
                    String reciverInfo =  order.getCommon().getReciverInfo();
                    if(StringUtils.isNotEmpty(reciverInfo)) {
                        address = JacksonsUtil.newInstance().json2Obj(reciverInfo, Address.class);
                    }
                    // 地址
                    String addressInfo = address.getAddress();
                    if(StringUtils.isNotEmpty(address.getAreaInfo())) {
                        addressInfo = address.getAreaInfo() + " " + address.getAddress();
                    }
                    mergeRows(sheet, rowIndex, colIndex, goodsList.size());   // 单元格合并
                    cell = row.createCell(colIndex++);
                    if(StringUtils.isNotEmpty(addressInfo)) {
                        if (addressInfo.length() > colWidth[colIndex-1] / 256) {     // 列宽
                            colWidth[colIndex-1] = addressInfo.length() * 256;
                        }
                        cell.setCellValue(addressInfo);
                    }
                    // 联系电话
                    mergeRows(sheet, rowIndex, colIndex, goodsList.size());   // 单元格合并
                    cell = row.createCell(colIndex++);
                    if(StringUtils.isNotEmpty(address.getMobPhone())) {
                        if (address.getMobPhone().length() > colWidth[colIndex-1] / 256) {     // 列宽
                            colWidth[colIndex-1] = address.getMobPhone().length() * 256;
                        }
                        cell.setCellValue(address.getMobPhone());
                    }
                    // 发票信息
                    String invoiceInfo = order.getCommon().getInvoiceInfo();
                    mergeRows(sheet, rowIndex, colIndex, goodsList.size());   // 单元格合并
                    cell = row.createCell(colIndex++);
                    if(StringUtils.isNotEmpty(invoiceInfo)) {
                        cellStyle.setWrapText(true);

                        Invoice invoice = JacksonsUtil.newInstance().json2Obj(invoiceInfo, Invoice.class);
                        invoiceInfo = "发票类型：" + invoice.getInvTitle() + "\r\n 名称：" + invoice.getInvCompany() + "\r\n 税号：" + invoice.getInvCode();
                        cell.setCellValue(new HSSFRichTextString(invoiceInfo));
                        cell.setCellStyle(cellStyle);

                        // 列宽
                        if (invoiceInfo.length() / 3 > colWidth[colIndex-1] / 256) {
                            colWidth[colIndex-1] = invoiceInfo.length() * 256 / 2;
                        }
                    }
                    // 留言
                    String message = order.getCommon().getOrderMessage();
                    mergeRows(sheet, rowIndex, colIndex, goodsList.size());   // 单元格合并
                    cell = row.createCell(colIndex++);
                    if(StringUtils.isNotEmpty(message)) {
                        cell.setCellValue(message);

                        if (message.length() > colWidth[colIndex-1] / 256) {     // 列宽
                            colWidth[colIndex-1] = message.length() * 256;
                        }
                    }
                    // 备注
                    mergeRows(sheet, rowIndex, colIndex, goodsList.size());   // 单元格合并
                    cell = row.createCell(colIndex++);
                    cell.setCellValue("");

                    // 商品信息（第二件开始）
                    if (goodsList.size() > 1) {
                        for (int i=1; i< goodsList.size(); i++) {
                            // 商品信息从第六列开始
                            row = sheet.createRow(rowIndex++);
                            colIndex = 5;

                            goods = goodsList.get(i);
                            // 产品名称
                            cell = row.createCell(colIndex++);
                            if(StringUtils.isNotEmpty(goods.getGoodsName())) {
                                if (goods.getGoodsName().length() > colWidth[colIndex-1] / 256) {     // 列宽
                                    colWidth[colIndex-1] = goods.getGoodsName().length() * 256;
                                }
                                cell.setCellValue(goods.getGoodsName());
                            }
                            // 商品规格
                            goodsSpec = goods.getGoodsSpec();
                            if ("N;".equals(goodsSpec)) {
                                goodsSpec = "默认";
                            }
                            cell = row.createCell(colIndex++);
                            if(StringUtils.isNotEmpty(goodsSpec)) {
                                if (goodsSpec.length() > colWidth[colIndex-1] / 256) {     // 列宽
                                    colWidth[colIndex-1] = goodsSpec.length() * 256;
                                }
                                cell.setCellValue(goodsSpec);
                            }
                            // 商品数量
                            cell = row.createCell(colIndex++);
                            if (goods.getGoodsNum() != null) {
                                if (goods.getGoodsNum().toString().length() > colWidth[colIndex-1] / 256) {     // 列宽
                                    colWidth[colIndex-1] = goods.getGoodsNum().toString().length() * 256;
                                }
                                cell.setCellValue(goods.getGoodsNum());
                            }
                            // 成本单价
                            cell = row.createCell(colIndex++);
                            if (goods.getCostPrice() != null) {
                                if (goods.getCostPrice().toEngineeringString().length() > colWidth[colIndex-1] / 256) {     // 列宽
                                    colWidth[colIndex-1] = goods.getCostPrice().toEngineeringString().length() * 256;
                                }
                                cell.setCellValue(goods.getCostPrice().toEngineeringString());
                            }
                            // 成本金额
                            cell = row.createCell(colIndex++);
                            if (goods.getGoodsNum() != null && goods.getCostPrice() != null) {
                                BigDecimal costAmount = goods.getCostPrice().multiply(new BigDecimal(goods.getGoodsNum()));
                                if (costAmount.toEngineeringString().length() > colWidth[colIndex-1] / 256) {     // 列宽
                                    colWidth[colIndex-1] = costAmount.toEngineeringString().length() * 256;
                                }
                                cell.setCellValue(costAmount.toEngineeringString());
                            }
                            // 销售单价
                            cell = row.createCell(colIndex++);
                            if (goods.getGoodsPrice() != null) {
                                if (goods.getGoodsPrice().toEngineeringString().length() > colWidth[colIndex-1] / 256) {     // 列宽
                                    colWidth[colIndex-1] = goods.getGoodsPrice().toEngineeringString().length() * 256;
                                }
                                cell.setCellValue(goods.getGoodsPrice().toEngineeringString());
                            }
                            // 销售金额
                            cell = row.createCell(colIndex++);
                            if (goods.getGoodsNum() != null && goods.getGoodsPrice() != null) {
                                BigDecimal marketAmount = goods.getGoodsPrice().multiply(new BigDecimal(goods.getGoodsNum()));
                                if (marketAmount.toEngineeringString().length() > colWidth[colIndex-1] / 256) {     // 列宽
                                    colWidth[colIndex-1] = marketAmount.toEngineeringString().length() * 256;
                                }
                                cell.setCellValue(marketAmount.toEngineeringString());
                            }
                        }
                    }
                }

                // 自适应列宽度
                for (int i = 0; i < titleName.length; i++) {
                    // sheet.autoSizeColumn(i, true);
                    sheet.setColumnWidth(i, colWidth[i]);
                }
            }

            // 去掉UUID 的 -
            String filename = UUID.randomUUID().toString().replaceAll("-", "") + ".xls";

            String dir = request.getSession().getServletContext().getRealPath("/").concat(File.separator).concat("temp").concat(File.separator);
            File file = new File(dir);
            if (!file.exists()) {
                file.mkdirs();
            }

            final String fullname = dir + filename;
            new Timer().schedule(new TimerTask() {
                @Override
                public void run() {
                    new File(fullname).delete();
                }
            }, 600000);

            OutputStream os = new FileOutputStream(fullname);
            workbook.write(os);
            os.flush();
            os.close();

            ajaxReturnData.setResult(true);
            ajaxReturnData.setReturnStr(filename);

        } catch (Exception e) {
            ajaxReturnData.setResult(false);
            e.printStackTrace();
            logger.error(e.getLocalizedMessage());
        }
        return ajaxReturnData;
    }

    /**
     * 单元格合并（合并行）
     * @param sheet
     * @param rowIndex
     * @param colIndex
     * @param goodsSize
     */
    private void mergeRows(HSSFSheet sheet, int rowIndex, int colIndex, int goodsSize) {
        // 单元格合并
        int firstRow = rowIndex - 1;
        int lastRow = firstRow + goodsSize - 1;
        int firstCol = colIndex;
        int lastCol  = colIndex;

        // 只有一条时，不需要合并行
        if (goodsSize > 1) {
            CellRangeAddress cellRange = new CellRangeAddress(firstRow, lastRow, firstCol, lastCol);
            sheet.addMergedRegion(cellRange);
        }
    }


    @RequestMapping(value = "doCancel")
    public ModelAndView doCancelOrder(Order order,HttpServletRequest request) {
        MemberBase adminInfo = (MemberBase)request.getSession().getAttribute("memInfo");
        orderService.doCancelOrder(order,adminInfo);
        return new ModelAndView("redirect:/trade/order");
    }

    @RequestMapping(value = "order/orderDetail")
    public ModelAndView orderDetail(int orderId) {
        OrderVo orderVo= orderService.selectById(orderId);
        OrderCommonVo commonVo = orderVo.getCommon();
        if(!"".equals(commonVo.getReciverInfo())&&commonVo.getReciverInfo()!=null) {
            Address address = JacksonsUtil.newInstance().json2Obj(commonVo.getReciverInfo(), Address.class);
            commonVo.setAddress(address);
        }
        return new ModelAndView("trade/order/orderDetail","order",orderVo);
    }


    /**
     * 负责售后服务的方法
     * TODO 用于咨询方面的
     * @return
     */
    @RequestMapping(value="consultList")
    public ModelAndView consultList(HttpServletRequest request,ConsultSearchBean page) throws Exception {
        List consultTypeList = consultService.getConsultTypeList();
        ModelAndView modelAndView = new ModelAndView("trade/service/consultList","consultTypeList",consultTypeList);
        modelAndView.addObject("page", page);
        consultService.selectListByCondition(page);
        return modelAndView;
    }


    /**
     * 咨询类型
     * @return
     */
    @RequestMapping(value="consultList/consultTypeList")
    public ModelAndView consultList() throws Exception {
        List consultTypeList = consultService.getConsultTypeList();
        ModelAndView modelAndView = new ModelAndView("trade/service/consultTypeList","consultTypeList",consultTypeList);
        return modelAndView;
    }

    /**
     * 咨询类型
     * @return
     */
    @RequestMapping(value="consultList/consultTypeDelete")
    public ModelAndView consultTypeDelete(String ctId) throws Exception {
        consultService.deleteConsultTypeByPrimaryKey(Integer.valueOf(ctId));
        ModelAndView modelAndView = new ModelAndView("redirect:/trade/consultList/consultTypeList");
        return modelAndView;
    }

    /**
     * 咨询类型
     * @return
     */
    @RequestMapping(value="consultList/consultTypeAdd")
    public ModelAndView consultTypeAdd() throws Exception {
        ModelAndView modelAndView = new ModelAndView("trade/service/consultTypeAdd");
        return modelAndView;
    }

    /**
     * 咨询类型
     * @return
     */
    @RequestMapping(value="consultList/consultTypeAdddo")
    public ModelAndView consultTypeAdddo(ConsultType consultType) throws Exception {
        consultService.insertConsultType(consultType);
        ModelAndView modelAndView = new ModelAndView("redirect:/trade/consultList/consultTypeList");
        return modelAndView;
    }

    /**
     * 咨询类型
     * @return
     */
    @RequestMapping(value="consultList/consultTypeEdit")
    public ModelAndView consultTypeEdit(String ctId) throws Exception {
        ModelAndView modelAndView = new ModelAndView("trade/service/consultTypeEdit","consultType",consultService.selectConsultTypeByPrimaryKey(Integer.valueOf(ctId)));
        return modelAndView;
    }

    /**
     * 咨询类型
     * @return
     */
    @RequestMapping(value="consultList/consultTypeEditdo")
    public ModelAndView consultTypeEditdo(ConsultType consultType) throws Exception {
        consultService.updateConsultTypeByPrimaryKeySelective(consultType);
        ModelAndView modelAndView = new ModelAndView("redirect:/trade/consultList/consultTypeList");
        return modelAndView;
    }

    @RequestMapping(value="consultList/deleteConsultByIds")
    public ModelAndView deleteConsultByIds(ConsultSearchBean page,String [] ids) throws Exception {
        if(ids!=null) {
            List nList = Arrays.asList(ids);
            consultService.deleteByIds(nList);
        }
        return new ModelAndView("redirect:/trade/consultList?searchType="+page.getSearchType()+"&&ctId="+page.getCtId());
    }

    @RequestMapping("evaluationList")
    @AuthPassport
    public ModelAndView orderEvaluationList(EvaluateGoodsSearchBean page) {
        ModelAndView view = new ModelAndView("trade/evaluate/evaluationList");
        view.addObject("page", page);
        evaluateGoodsService.selectByCondation(page);
        return view;
    }

    @RequestMapping(value="deleteEvaluationByIds")
    public ModelAndView deleteEvaluationByIds(String [] ids) throws Exception {
        if(ids!=null) {
            List nList = Arrays.asList(ids);
            evaluateGoodsService.deleteByIds(nList);
        }
        return new ModelAndView("redirect:/trade/evaluationList");
    }

    @RequestMapping("complainList")
    @AuthPassport
    public ModelAndView complainList(ComplainSearchBean page) {
        ModelAndView view = new ModelAndView("trade/complain/complainList");
        view.addObject("page", page);
        complaintService.selectByCondition(page);
        return view;
    }

    @RequestMapping("complainList/complainSubjectList")
    @AuthPassport
    public ModelAndView complainSubjectList(ComplainSubject page) {
        ModelAndView view = new ModelAndView("trade/complain/complainSubjectList");
        view.addObject("page", page);
        complainSubjectService.selectByCondition(page);
        return view;
    }

    @RequestMapping("complainList/complainSubjectAdd")
    public ModelAndView complainSubjectAdd() {
        ModelAndView view = new ModelAndView("trade/complain/complainSubjectAdd");
        return view;
    }

    @RequestMapping("complaininfo")
    public ModelAndView complaininfo(Integer complainId) {
        ModelAndView view = new ModelAndView("trade/complain/complaininfo","complain",complaintService.selectByPrimaryKey(complainId));
        view.addObject("complainTalk", complainTalkMapper.selectByCondition(new ComplainTalk())) ;
        return view;
    }

    @RequestMapping("complainList/complainSubjectAdddo")
    public ModelAndView complainSubjectAdddo(ComplainSubject page) {
        ModelAndView view = new ModelAndView("redirect:/trade/complainList/complainSubjectList");
        complainSubjectService.insert(page);
        return view;
    }

    //更新投诉状态
    @RequestMapping(value="updateComplainById")
    public ModelAndView deleteComplainByIds(ComplainVo complainVo) throws Exception {
        complaintService.updateComplain(complainVo);
        return new ModelAndView("redirect:/trade/complainList");
    }

    @RequestMapping(value="deleteComplainByIds")
    public ModelAndView deleteComplainByIds(String [] ids) throws Exception {
        if(ids!=null) {
            List nList = Arrays.asList(ids);
            complaintService.deleteByIds(nList);
        }
        return new ModelAndView("redirect:/trade/complainList");
    }
    @RequestMapping(value="deleteComplainSubjectById")
    public ModelAndView deleteComplainSubjectByIds(String complainSubjectId) throws Exception {
        if(complainSubjectId!=null) {
            complainSubjectService.deleteByPrimaryKey(Integer.valueOf(complainSubjectId));
        }
        return new ModelAndView("redirect:/trade/complainList/complainSubjectList");
    }

    @RequestMapping(value="getcomplaintalkList")
    public  @ResponseBody  List<ComplainTalk>  complaintalkList(ComplainTalk complainTalk) throws Exception {
        return complainTalkMapper.selectByCondition(complainTalk);
    }

    @RequestMapping(value="publishComplainTalk")
    public  @ResponseBody String  publishComplainTalk(ComplainTalk complainTalk,HttpServletRequest request) throws Exception {
        MemberBase adminInfo = (MemberBase)request.getSession().getAttribute("memInfo");
        complainTalk.setTalkDatetime(DateUtil.unixTimeStampInt().intValue());
        complainTalk.setTalkMemberName(adminInfo.getUserName());
        complainTalk.setTalkMemberType("3");
        complainTalk.setTalkAdmin(0);
        complainTalk.setTalkMemberId(adminInfo.getUserId());
        complainTalk.setTalkState((byte) 1);
        int i = complainTalkMapper.insert(complainTalk);
        if(i==1){
            return "success";
        }else{
            return "failed";
        }
    }

    @RequestMapping(value="closeComplaint")
    public  ModelAndView closeComplaint(ComplainVo complain,HttpServletRequest request) throws Exception {
        MemberBase adminInfo = (MemberBase)request.getSession().getAttribute("memInfo");
        complain.setComplainState(99);
        complain.setFinalHandleDatetime(DateUtil.unixTimeStampInt().intValue());
        complain.setFinalHandleMemberId(adminInfo.getUserId());
        complaintService.updateComplain(complain);
        ModelAndView view = new ModelAndView("trade/complain/complaininfo","complain",complaintService.selectByPrimaryKey(complain.getComplainId()));
        view.addObject("complainTalk", complainTalkMapper.selectByCondition(new ComplainTalk())) ;
        return view;
    }
    @RequestMapping(value="forbitTalk")
    public  @ResponseBody String forbitTalk(Integer talkId,HttpServletRequest request){
        MemberBase adminInfo = (MemberBase)request.getSession().getAttribute("memInfo");
        ComplainTalk complainTalk = new ComplainTalk();
        complainTalk.setTalkId(talkId);
        complainTalk.setTalkAdmin(adminInfo.getUserId());
        int i = complainTalkMapper.updateByPrimaryKeySelective(complainTalk);
        if(i==1){
            return "success";
        }else{
            return "failed";
        }
    }
    /**
     * 新增退款原因
     * @return
     */
    @RequestMapping(value="refund/reasonadd")
    public ModelAndView reasonadd() throws Exception {
        ModelAndView modelAndView = new ModelAndView("trade/refund/reasonadd");
        return modelAndView;
    }

    @RequestMapping(value="refund/reasonedit")
    public ModelAndView reasonedit(Integer reasonId) throws Exception {
        ModelAndView modelAndView = new ModelAndView("trade/refund/reasonedit","info",refundReasonMapper.selectByPrimaryKey(reasonId));
        return modelAndView;
    }

    /**
     * 退款原因
     * @return
     */
    @RequestMapping(value="refund/reasonList")
    public ModelAndView reasonList(RefundReason refundReason) throws Exception {
        List reasonList = refundReasonMapper.selectByCondition(refundReason);
        refundReason.setResultList(reasonList);
        ModelAndView modelAndView = new ModelAndView("trade/refund/reasonList","page",refundReason);
        return modelAndView;
    }

    /**
     * 退款原因
     * @return
     */

    @RequestMapping(value="refund/reasonadddo")
    public ModelAndView reasonadddo(RefundReason refundReason) throws Exception {
        refundReason.setUpdateTime(DateUtil.unixTimeStampInt().intValue());
        refundReasonMapper.insert(refundReason);
        ModelAndView modelAndView = new ModelAndView("redirect:/trade/refund/reasonList");
        return modelAndView;
    }



    @RequestMapping(value="refund/reasoneditdo")
    public ModelAndView reasoneditdo(RefundReason refundReason) throws Exception {
        refundReasonMapper.updateByPrimaryKeySelective(refundReason);
        ModelAndView modelAndView = new ModelAndView("redirect:/trade/refund/reasonList");
        return modelAndView;
    }

    //    删除退货原因
    @RequestMapping(value="refund/reasonrm")
    public ModelAndView reasonrm(Integer reasonId) throws Exception {
        refundReasonMapper.deleteByPrimaryKey(reasonId);
        ModelAndView modelAndView = new ModelAndView("redirect:/trade/refund/reasonList");
        return modelAndView;
    }
}
